import os
import shutil
import requests
import re
from util.logger import get_logger
logger = get_logger("高清壁纸网站.log",__name__)

try:
    logger.info("程序启动了")

    root = 'static/高清壁纸网站'
    if os.path.exists(root):
        shutil.rmtree(root)
    os.makedirs(root)


    url='https://www.hdbz.net/'
    response = requests.get(url)
    if response.status_code == 200:
        response_text = response.content.decode('utf-8')
        pic_list = re.findall(r'<a href="(/wallpaper/\d{6}/\d{6}.html)".*?title="(.*?)" data-resolution=".*?".*?data-original="(.*?)".*?<div class="resolution">(.*?)</div>.*?</a>', response_text, re.S)
        for pic in pic_list:
            detail_url = f"https://www.hdbz.net{pic[0]}"
            title = pic[1]
            thumbnail_image_url = pic[2]
            resolution = pic[3]
            # 保存缩略图
            logger.debug(f"开始保存 {title} 的缩略图")
            thumbnail_response = requests.get(thumbnail_image_url)
            if thumbnail_response.status_code == 200:
                with open(f'{root}/{title}_thumbnail.jpg', "wb") as f:
                    f.write(thumbnail_response.content)
            logger.debug(f"保存 {title}_thumbnail.jpg 完成")
            # 爬取详情页
            logger.debug(f"开始爬取 {title} 的详情页")
            detail_response = requests.get(detail_url)
            if detail_response.status_code == 200:
                detail_text = detail_response.content.decode('utf-8')
                preview_url = re.search(r'<div class="pic-preview">.*?src="(.*?)" />', detail_text, re.S)
                preview_url = preview_url.group(1)
                # 保存详情图
                logger.debug(f"开始保存 {title} 的详情图")
                preview_response = requests.get(preview_url)
                if preview_response.status_code == 200:
                    with open(f'{root}/{title}_preview.jpg', "wb") as f:
                        f.write(preview_response.content)
                logger.debug(f"保存 {title}_preview.jpg 完成")
            break
except Exception as e:
    logger.error(e)

logger.info("程序运行完成")
